﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Server;
using Microsoft.Office.Server.SocialData;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
 

namespace Schwazzle.Core.Services
{
    public class TagsService
    {
        string _currentSiteName;
        const string _tagName = "4Me";
        const int _itemReturnLimit = 15;

        public TagsService(string SiteName)
        {
            _currentSiteName = SiteName;
        }

        public SocialUrl[] GetTagsByName(string TagName, string UsernameWithDomain)
        {
            using (SPSite site = new SPSite(_currentSiteName))
            {
                //// Get the context of the service application
                 SPServiceContext context = SPServiceContext.GetContext(site);
 
                ////UserProfileManager is used to create a UserProfile object and thenretrieve the corresponding data from the user profile database.
                 UserProfileManager userProfileManager =new UserProfileManager(context);
 
                ////Gets the UserProfile object for the specified account name
                 UserProfile userProfile = userProfileManager.GetUserProfile(UsernameWithDomain); 
 
                //// SocialTagManager - Contains methods and properties used tomanipulate social tag data
                 SocialTagManager socialTagManager = new SocialTagManager(context);
 
                TaxonomySession session = new TaxonomySession(site);
                
                //TODO: Make this more flexible. Field name must match termset name. TermStore name defined in config file.
                TermStore store = session.TermStores["Managed Metadata Service"];
                TermSetCollection termsets = store.GetTermSets("Keywords", 1033);
                TermSet termset = termsets["Keywords"];
                
                TermCollection terms = termset.GetTerms(_tagName, false);
            
                if (terms.Count == 0)
                {
                    Term newTerm = termset.CreateTerm(_tagName, 1033);
                    store.CommitAll();
                    terms = termset.GetTerms(_tagName, false);
                    //throw new KeyNotFoundException("Could not find metadata field value " + termToFind + ": " + Field.ToString()); }
                }
                Term term = terms[0];
                //// GetTags(userProfile) method is used to retrieve an array ofSocialTag objects for the specified user.
                SocialUrl[] urls = socialTagManager.GetAllUrls(term);
                return urls;
            }
        }

        public List<SPListItem> GetListItemChanges(string TagName, string UsernameWithDomain)
        {
            SocialUrl[] urls = GetTagsByName(TagName, UsernameWithDomain);
            List<SPListItem> listItems = new List<SPListItem>();
            foreach(SocialUrl url in urls)
            {
                using (SPSite site = new SPSite(url.Url.AbsoluteUri))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.GetListFromUrl(url.Url.AbsoluteUri);
                        // Construct a query.
                        SPChangeQuery query = new SPChangeQuery(true, true);
                        query.FetchLimit = 25;
                        query.Group = true;
                        query.GroupMembershipAdd = true;
                        query.Add = true;
                        query.ContentType = false;
                        query.Folder = false;
                        query.View = false;
                        //query.ChangeTokenStart = new SPChangeToken(SPChangeCollection.CollectionScope.List, Guid.NewGuid(), DateTime.Now.AddDays(-14));
                        SPChangeCollection changes = list.GetChanges(query);
                        foreach (SPChange change in changes)
                        {
                            SPChangeItem changeItem = change as SPChangeItem;
                            if (changeItem != null)
                            {
                                SPListItem item = list.Items[changeItem.UniqueId] as SPListItem;
                                listItems.Add(item);
                            }
                        }
                    }
                }
            }
            return listItems;
        }

        public List<SPListItem> GetColleaguesTags(string TagName, string UsernameWithDomain)
        {
            List<SPListItem> items = new List<SPListItem>();
            using (SPSite site = new SPSite(_currentSiteName))
            {
                //Get Server context
                SPServiceContext context = SPServiceContext.GetContext(site);
                //Get UserProfileManager for the site cocntext
                UserProfileManager profileManager = new UserProfileManager(context);
                UserProfile userProfile;
                if (profileManager.UserExists(UsernameWithDomain))
                {
                    userProfile = profileManager.GetUserProfile(UsernameWithDomain);
                    SPUser user;
                    SPWeb web = site.OpenWeb();
                    user = web.AllUsers[userProfile["AccountName"].ToString()];
                    ColleagueManager colleagues = userProfile.Colleagues;
                    foreach (Colleague colleague in colleagues.GetItems())
                    {
                        List<SPListItem> colleagueItems = this.GetListItemChanges(TagName, colleague.Profile.DisplayName);
                        foreach (SPListItem colleagueItem in colleagueItems)
                        {
                            if (colleagueItem.DoesUserHavePermissions(user, SPBasePermissions.ViewListItems))
                            { items.Add(colleagueItem); }
                        }
                    }
                }
            }
            return items;
        }
    }
}
